

#include "ntp.h"
#include "serial.h"
#include "oled.h"

// 创建UDP和NTP客户端实例
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "ntp.aliyun.com", 8 * 3600); // 使用阿里云NTP服务器，设置东八区

void ntpInit() {
    serialPrint("初始化NTP客户端...");
    timeClient.begin();
    serialPrint("NTP客户端初始化完成");
}

String ntpGetTime() {
    timeClient.update();  // 更新时间
    
    // 获取时分秒
    int hours = timeClient.getHours();
    int minutes = timeClient.getMinutes();
    int seconds = timeClient.getSeconds();
    
    // 格式化时间字符串 (HH:MM:SS)
    char timeStr[9];
    sprintf(timeStr, "%02d:%02d:%02d", hours, minutes, seconds);
    return String(timeStr);
}

String ntpGetDate() {
    timeClient.update();  // 更新时间
    
    // 将epoch时间转换为日期
    time_t epochTime = timeClient.getEpochTime();
    struct tm *ptm = gmtime ((time_t *)&epochTime);
    
    int year = ptm->tm_year + 1900;
    int month = ptm->tm_mon + 1;
    int day = ptm->tm_mday;
    
    // 格式化日期字符串 (YYYY-MM-DD)
    char dateStr[11];
    sprintf(dateStr, "%04d-%02d-%02d", year, month, day);
    return String(dateStr);
}

bool ntpSync() {
    serialPrint("正在同步网络时间...");
    oledShow(0, 16, "正在同步网络时间...");
    
    // 尝试强制更新时间
    if (timeClient.forceUpdate()) {
        serialPrint("时间同步成功");
        oledClear();
        oledShow(0, 16, "时间同步成功");
        oledShow(0, 32, "日期: " + ntpGetDate());
        oledShow(0, 48, "时间: " + ntpGetTime());
        return true;
    } else {
        serialPrint("时间同步失败");
        oledClear();
        oledShow(0, 16, "时间同步失败");
        return false;
    }
}
